package com.ruoyi.partybuilding.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.partybuilding.common.DataUtil;
import com.ruoyi.partybuilding.common.EQueryController;
import com.ruoyi.partybuilding.common.TableDataInfoRows;
import com.ruoyi.partybuilding.domain.Message;
import com.ruoyi.partybuilding.domain.ReviewStaffs;
import com.ruoyi.partybuilding.domain.ReviewUser;
import com.ruoyi.partybuilding.domain.vo.DeptOrgVo;
import com.ruoyi.partybuilding.service.impl.*;
import lombok.var;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.partybuilding.domain.Review;
import io.swagger.annotations.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 评议Controller
 * 
 * @author he-liangliang@outlook.com
 * @date 2024-11-27
 */
@Api(tags = "评议")
@RestController
@RequestMapping("/partybuilding/Review")
public class ReviewController extends EQueryController<Review> {


    @Resource
    ReviewServiceImpl reviewService;
    @Resource
    OrgServiceImpl orgService;
    /**
     * 查询评议列表
     */
    @ApiOperation("列表")
    @PreAuthorize("@ss.hasPermi('partybuilding:Review:list')")
    @GetMapping("/list")
    @DataScope
    public TableDataInfoRows<Review> list(Review review, PageDomain pageRequest) {

        var reList = queryPage(review, pageRequest);
        //
        var orgList = orgService.deptVoList(null).getData();
        var reMaps = DataUtil.findSetRe(reList.getData().getContent(), orgList, (p, p1) -> Objects.equals(p.getDeptId(), p1.getDeptId()), (p, p2) -> {
            Map map = DataUtil.toMap(p, null);
            map.put("deptName", p2.getDeptName());
            return map;
        });
        var re = new TableDataInfoRows(reList.getData().getTotalElements(), reMaps);
        return re;
    }


    R<Page<Review>> queryPage(Review whereObj, PageDomain pageRequest) {
        List<Long> deptIds = null;
        if (whereObj != null && whereObj.getDeptId() != null) {
            deptIds = new ArrayList<>();
            deptIds.add(whereObj.getDeptId());
            var depts = orgService.allChilds(whereObj.getDeptId()).getData();
            if (depts.size() > 0)
                deptIds.addAll(depts.stream().map(DeptOrgVo::getDeptId).collect(Collectors.toList()));
        }
        pageRequest = gainPageDomain(pageRequest);
        var ids = deptIds == null ? null : deptIds.toArray(new Long[0]);
        var pitem = queryHelper.query().queryable(tClass)
                .whereObject(whereObj != null, whereObj)
                .where(deptIds != null, p -> p.in(Review::getDeptId, ids));
        var pData = pitem.orderByDesc(p->p.column(Review::getId)).toPageResult(pageRequest.getPageNum(), pageRequest.getPageSize());
        var listSet = reviewService.statusSetByNow(new Date(),pData.getData().toArray(new Review[0]));
        queryHelper.query().updatable(listSet).executeRows();
        var page = new PageImpl<>(pData.getData(), Pageable.unpaged(), pData.getTotal());
        return R.ok(page);
    }



    /**
     * 导出评议列表
     */
    @ApiOperation("导出")
    @PreAuthorize("@ss.hasPermi('partybuilding:Review:export')")
    @Log(title = "评议", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Review review, PageDomain pageRequest) {
       super.export(review,pageRequest,null,response);
    }

    /**
     * 获取评议详细信息
     */
    @ApiOperation("详情,会返回评议人员列表")
    @PreAuthorize("@ss.hasPermi('partybuilding:Review:query')")
    @GetMapping(value = "/{id}")
    public R<Review> getInfo(@PathVariable("id") Long id) {
        return R.ok(equeryable().include(p->p.many(Review::getStaffs)).whereById(id).firstOrNull());
    }
    @Resource
    MemberServiceImpl memberService;

    @Resource
    MessageServiceImpl messageService;
    /**
     * 新增评议
     */
    @ApiOperation("新增")
    @PreAuthorize("@ss.hasPermi('partybuilding:Review:add')")
    @Log(title = "评议", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @Transactional()
    public R<Long> add(@RequestBody Review review) {
        //review.setStatus(0);
        review.setCreateBy(getUsername());
        review.setCreateTime(new Date());
        review.setUpdateBy(getUsername());
        review.setUpdateTime(new Date());
        reviewService.statusSetByNow(new Date(),review);
        var re = queryHelper.query().insertable(review).executeRows(true);
        var list = review.getStaffs();
        for (var item : list) {
            item.setReviewId(review.getId());
            item.setCreateBy(getUsername());
            item.setCreateTime(new Date());
        }
        //补充用户信息
        var uList = memberService.queryByIds(list.stream().map(ReviewStaffs::getUserId).distinct().collect(Collectors.toList()));
        orgService.deptSet(uList, (p, p2) -> p2.setDeptName(p.getDeptName()));
        list.forEach(p -> {
            var rvTmp = uList.stream().filter(x -> Objects.equals(x.getUserId(), p.getUserId())).findFirst();
            rvTmp.ifPresent(x -> {
                p.setUserName(x.getNickName());
                p.setAvatar(x.getAvatar());
                p.setDeptId(x.getDeptId());
                p.setDeptName(x.getDeptName());
            });
        });
        queryHelper.query().insertable(list).executeRows();
        //发生评议消息
        sendMsg(review);
        return R.ok();
    }

    private void sendMsg(Review review) {
        var list = review.getStaffs();
        //var ruList = list.stream().filter(p -> p.getType() == 0).collect(Collectors.toList());
        var ruList2 = list.stream().filter(p -> p.getType() == 1).collect(Collectors.toList());
        var msgList = new ArrayList<Message>();
        ruList2.forEach(p -> {
            var msg = new Message();
            msg.setUserId(p.getUserId());
            msg.setUserName(p.getUserName());
            msg.setTitle("评议提醒：" + review.getTitle());
            msg.setContent("有新的评议内容待评议，评议标题：" + review.getTitle());
            msg.setSourceId(review.getId() + "");
            msg.setSourceName("sys.review.add");
            msg.setCreateBy(getUsername());
            msg.setStatus(0l);
            msg.setCreateTime(new Date());
            msg.setType(0l);
            //msg.setRemark("测试长度1234567");
            msgList.add(msg);
        });
        messageService.sendMsg(msgList);
    }


    /**
     * 修改评议
     */
    @ApiOperation("编辑")
    @PreAuthorize("@ss.hasPermi('partybuilding:Review:edit')")
    @Log(title = "评议", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public R<Long> edit(@RequestBody Review review) {

        //super.getInfo(review.getId());
        review.setUpdateBy(getUsername());
        review.setUpdateTime(new Date());
        return super.edit(review);
    }

    /**
     * 删除评议
     */
    @ApiOperation("删除")
    @PreAuthorize("@ss.hasPermi('partybuilding:Review:remove')")
    @Log(title = "评议", businessType = BusinessType.DELETE)
    @PostMapping("remove/{ids}")
    public R<Long> remove(@PathVariable Long[] ids) {
        var isRun=queryHelper.queryable(ReviewUser.class).where(p->p.in(ReviewUser::getReviewId,ids)).any();
        if(isRun)
            return R.fail("已进行中的评议不允许删除");
        return super.remove(ids);
    }
}
